package netWork;

import com.sun.deploy.net.socket.UnixDomainSocket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class My_ThreadServer {
    private ServerSocket serverSocket = null;

    public My_ThreadServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        while (true) {
            Socket receve = serverSocket.accept();
            Thread thread = new Thread(() -> {
                processConnection(receve);
            });
            thread.start();
        }

    }
    public void start2() throws IOException {
        while (true) {
            Socket receve = serverSocket.accept();
            ExecutorService pool= Executors.newScheduledThreadPool(10);
            pool.submit(new Runnable() {
                @Override
                public void run() {
                    processConnection(receve);
                }
            });


        }

    }

    private void processConnection(Socket clientSocket) {
        System.out.printf("[%s:%d] 客户端建立连接!\n", clientSocket.getInetAddress().toString(), clientSocket.getPort());
        try (InputStream inputStream = clientSocket.getInputStream()) {
            try (OutputStream outputStream = clientSocket.getOutputStream()) {
                Scanner in = new Scanner(inputStream);
                while (true) {
                    if (!in.hasNext()) {
                        System.out.printf("[%s:%d] 客户端断开连接!\n", clientSocket.getInetAddress().toString(), clientSocket.getPort());
                        break;
                    }
                    /*因为tcp是建立链接,所以不用socket发送,直接写入就行
                    * udpu*/
                    String request = in.next();
                    String response = process(request);
                    PrintWriter printWriter = new PrintWriter(outputStream);
                    printWriter.println(response);
                    printWriter.flush();

                    System.out.printf("[%s:%d] req: %s, resp: %s\n", clientSocket.getInetAddress().toString(),
                            clientSocket.getPort(), request, response);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    private String process(String request) {
        return request;
    }
    public static void main(String[] args) throws IOException {
        TcpThreadEchoServer server = new TcpThreadEchoServer(9090);
        server.start();
    }

}